package com.wang.eduservice.controller;


import com.wang.commonutils.R;
import com.wang.eduservice.client.VodClient;
import com.wang.eduservice.entity.EduVideo;
import com.wang.eduservice.service.EduVideoService;
import com.wang.servicebase.exceptionhandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-11-19
 */
@RestController
@RequestMapping("/eduservice/eduvideo")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    //注入VodClient
    @Autowired
    private VodClient vodClient;

    /**
     * 添加小节
     * @param eduVideo
     * @return
     */
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        videoService.save(eduVideo);
        return R.ok();
    }

    /**
     * 删除小节
     * @return
     */
    //TODO后面这个发那个发需要完善：删除小节的时候，同时把里面的视频删除
    @DeleteMapping("/{id}")
    public R deleteVideo(@PathVariable String id){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String sourceId = eduVideo.getVideoSourceId();
        //判断是否为空
        if (!StringUtils.isEmpty(sourceId)){
            //调用方法删除视频id
            R result = vodClient.removeAlyVideo(sourceId);
            if (result.getCode()==20001){
                throw new GuliException(20001,"删除视频失败，熔断器...");
            }
        }
        //删除小节
        videoService.removeById(id);
        return R.ok();
    }

    /**
     * 修改小节
     * @param eduVideo
     * @return
     */
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        videoService.updateById(eduVideo);
        return R.ok();
    }
    //
    @GetMapping("/getVideo/{videoId}")
    public R getVideo(@PathVariable String videoId){
        EduVideo eduVideo = videoService.getById(videoId);
        return R.ok().data("video",eduVideo);
    }
}

